//
//  DownloadProgressBar.m
//  Alfresco
//
//  Created by Michael Muller on 10/14/09.
//  Copyright 2010 Zia Consulting.  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
//

// this code id based on: http://pessoal.org/blog/2009/02/09/iphone-sdk-formatting-a-numeric-value-with-nsnumberformatter/

#import "DownloadProgressBar.h"
#import "Utility.h"

#define kDownloadCounterTag 1

@implementation DownloadProgressBar

@synthesize fileData;
@synthesize totalFileSize;
@synthesize progressView;
@synthesize progressAlert;
@synthesize delegate;
@synthesize filename;

- (void) dealloc {
	[fileData release];
	[progressView release];
	[progressAlert release];
	[filename release];
	[super dealloc];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	NSMutableData *data = [[NSMutableData alloc] init];
    self.fileData = data;
	[data release];
    self.totalFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.fileData appendData:data];
	
    NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.fileData length]];
    NSNumber *progress = [NSNumber numberWithFloat:([resourceLength floatValue] / [self.totalFileSize floatValue])];
    progressView.progress = [progress floatValue];
	
    const unsigned int bytes = 1024 * 1024;
    UILabel *label = (UILabel *)[progressAlert viewWithTag:kDownloadCounterTag];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setPositiveFormat:@"##0.00"];
    NSNumber *partial = [NSNumber numberWithFloat:([resourceLength floatValue] / bytes)];
    NSNumber *total = [NSNumber numberWithFloat:([self.totalFileSize floatValue] / bytes)];
    label.text = [NSString stringWithFormat:@"%@ MB of %@ MB", [formatter stringFromNumber:partial], [formatter stringFromNumber:total]];
    [formatter release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [progressAlert dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	if (self.delegate) {
		[delegate download: self completeWithData:self.fileData];
	}
	[progressAlert dismissWithClickedButtonIndex:0 animated:NO];
}

+ (DownloadProgressBar *) createAndStartWithURL:(NSURL*)url delegate:(id <DownloadProgressBarDelegate>)del message:(NSString *)msg filename:(NSString *)fname {

	DownloadProgressBar *bar = [[DownloadProgressBar alloc] init];

	// create a modal alert
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:msg message:@"Please wait..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    bar.progressAlert = alert;
	[alert release];
	
	// create a progress bar and put it in the alert
	UIProgressView *progress = [[UIProgressView alloc] initWithFrame:CGRectMake(30.0f, 80.0f, 225.0f, 90.0f)];
    bar.progressView = progress;
    [progress setProgressViewStyle:UIProgressViewStyleBar];
	[progress release];
	[bar.progressAlert addSubview:bar.progressView];
	
	// create a label, and add that to the alert, too
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(90.0f, 90.0f, 225.0f, 40.0f)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:12.0f];
    label.text = @"";
    label.tag = kDownloadCounterTag;
    [bar.progressAlert addSubview:label];

	// show the dialog
	[bar.progressAlert show];
	
	// who should we notify when the download is complete?
	bar.delegate = del;

	// save the filename
	bar.filename = fname;
	
	// start the download
	NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
	[NSURLConnection connectionWithRequest:requestObj delegate:bar];

	return bar;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
	NSString *user = userPrefUsername();
	NSString *pass = userPrefPassword();
	NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:user password:pass persistence:NSURLCredentialPersistenceNone];
	[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
	[credential release];
}

@end
